package com.alibaba.algo.apiimpl.feign;

import com.alibaba.algo.apiimpl.user.DingService;
import com.alibaba.algo.apiimpl.user.SysEmployeeServiceImpl;
import com.alibaba.algo.apiimpl.user.SysUserCacheServiceImpl;
import com.alibaba.algo.apiimpl.user.SysUserEmployeeServiceImpl;
import com.alibaba.algo.apiimpl.user.SysUserServiceImpl;
import com.alibaba.algo.constants.Constants;
import com.alibaba.algo.cooperation.common.BaseResult;
import com.alibaba.algo.cooperation.feign.service.UserFeignService;
import com.alibaba.algo.cooperation.feign.vo.req.*;
import com.alibaba.algo.cooperation.feign.vo.req.SelectUserListByAppRequestVO;
import com.alibaba.algo.cooperation.feign.vo.res.*;
import com.alibaba.algo.cooperation.usercenter.GlobalResultStatus;
import com.alibaba.algo.cooperation.usercomponent.vo.req.user.*;
import com.alibaba.algo.cooperation.usercomponent.vo.res.user.EmployeeOrgResVO;
import com.alibaba.algo.cooperation.usercomponent.vo.res.user.EmployeePositionResVO;
import com.alibaba.algo.cooperation.usercomponent.vo.res.user.SelectResourceActionListVO;
import com.alibaba.algo.core.base.YesOrNo;
import com.alibaba.algo.core.exception.BaseException;
import com.alibaba.algo.domain.user.SysCurrentOrgDomain;
import com.alibaba.algo.domain.user.SysEmployeeDomain;
import com.alibaba.algo.domain.user.SysEmployeeGroupDomain;
import com.alibaba.algo.domain.user.SysEmployeeOrgDomain;
import com.alibaba.algo.domain.user.SysEmployeePositionDomain;
import com.alibaba.algo.domain.user.SysGroupDomain;
import com.alibaba.algo.domain.user.SysResourceDomain;
import com.alibaba.algo.domain.user.SysRoleResourceActionDomain;
import com.alibaba.algo.domain.user.SysRoleResourceDomain;
import com.alibaba.algo.domain.user.SysUserDomain;
import com.alibaba.algo.domain.user.SysUserEmployeeDomain;
import com.alibaba.algo.domain.user.SysUserRoleDomain;
import com.alibaba.algo.dtos.user.UserOrgInfoResDTO;
import com.alibaba.algo.entity.user.SysCurrentOrg;
import com.alibaba.algo.entity.user.SysEmployee;
import com.alibaba.algo.entity.user.SysGroup;
import com.alibaba.algo.entity.user.SysUser;
import com.alibaba.algo.enums.SysUserPassWdSaltEnum;
import com.alibaba.algo.exception.BaseErrorCode;
import com.alibaba.algo.exception.SysEmployeeErrorCode;
import com.alibaba.algo.exception.SysUserErrorCode;
import com.alibaba.algo.util.StringUtil;
import com.alibaba.algo.utils.ConverterUtil;
import com.alibaba.algo.utils.RSAUtils;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.response.OapiV2UserGetResponse.UserGetResponse;
import com.xxl.sso.core.login.SsoTokenLoginHelper;
import com.xxl.sso.core.user.XxlSsoUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author Fan.tianpeng
 * @date 2021/5/8 10:42
 */
@Slf4j
@RestController
public class UserFeignServiceImpl implements UserFeignService {

    @Value("${rsa.privateKey:MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAICcHrWOTVO+M/EnPCyY8UNCJkmPqVYBcrdtORVLyp+YWMAFe+TNHBog303cyHs563Dh47Mj7TJD+6JfGQkh0vN1M6JGwHBm26J975B8CKaKtYTnIkk56aSYzd8VYtc1ZbG0huh6QVB0v1YI2o/4+YHun3QdWYzLJ+R6FTcgP4gRAgMBAAECgYALi/jF3CzdI+qN8DPa3TBsFXhSim9tpVujVE8XtmJOyeLN+rAQ7sljHyhtWTE2vxCAZgeHgeY96RSik18wDrVdvKLF/KH0DngRebJmJiILTyJJKISJ+E1douDc31vWVdjm3yu4MRxusbKTC1LegGnTX4iyUueH4QmqgdG6fRvTcQJBAOxC26KECSnOwZ1wXSd+PMk/LgTRaiM99maO5iynlGYHf1lUBzvndi8oEoiaw4HaPH1aGEaLfplNtRrPKprZGl8CQQCLWtInSLrBTwNCIkZGyKdPwB2uCF2/KWu0qSRoQ/nRUMPX3c5pe8wVJ61nR4z5oaFFlgdG+XExnGx6wqRTs1OPAkBvft3HxCfO4xPcCLrteFWXY4mEHI/KMeOmYqmdSThvLfqbXVxMmN7dQjv824yIK0WAopPyNsJ39oQRMtMYYHxhAkEAhA4Uh9WL5BOT6t+/6OPMaO6NMZYMAFKoFhMSxRtlaM04SR+PsrX1tzZaRDyxgv1/bgm167QFaBXrVomMXyTYUQJAbsqsHRRT8+Twh6nW74v1NGMnofni4XvoJq8d/9et0uboLPz2JEM+eUqJIu1989UOEVq+gnz+BF9vd4l2j2JKMA==}")
    private String rsaPrivateKey;
    @Value("${clientId:sfcmos}")
    private String clientId;
    @Value("${clientSecret:sfcmos44b98b297f1011ec877900163e0f4018}")
    private String clientSecret;


    @Autowired
    private SysUserDomain sysUserDomain;

    @Autowired
    private SysUserRoleDomain sysUserRoleDomain;

    @Autowired
    private SysUserEmployeeDomain sysUserEmployeeDomain;

    @Autowired
    private SysEmployeePositionDomain sysEmployeePositionDomain;

    @Autowired
    private SysEmployeeOrgDomain sysEmployeeOrgDomain;

    @Autowired
    private SysEmployeeGroupDomain sysEmployeeGroupDomain;

    @Autowired
    private SysRoleResourceActionDomain sysRoleResourceActionDomain;
    @Autowired
    private SysCurrentOrgDomain sysCurrentOrgDomain;
    @Autowired
    private DingService dingService;

    @Autowired
    private SysGroupDomain sysGroupDomain;

    @Autowired
    private SysUserServiceImpl sysUserService;
    @Autowired
    private SysEmployeeServiceImpl sysEmployeeService;
    @Autowired
    private SysEmployeeDomain sysEmployeeDomain;
    @Autowired
    private SysUserEmployeeServiceImpl sysUserEmployeeService;
    @Autowired
    private SysResourceDomain sysResourceDomain;
    @Autowired
    private SysRoleResourceDomain sysRoleResourceDomain;
    @Autowired
    private SysUserCacheServiceImpl sysUserCacheService;

    /**
     * 通过用户账号和密码查询用户详情
     *
     * @param vo 用户名
     * @return 用户列表
     */
    @Override
    public BaseResult<LoginUserInfoResVO> checkLogin(SelectUserLoginReqVO vo) {
        // 校验用户账号为空
        if (StringUtils.isEmpty(vo.getUserAccount())) {
            throw new BaseException(BaseErrorCode.USER_ACCOUNT_IS_NULL.getCode(), BaseErrorCode.USER_ACCOUNT_IS_NULL.getMessage());
        }
        // 校验用户密码为空
        if (StringUtils.isEmpty(vo.getPassWd())) {
            throw new BaseException(BaseErrorCode.USER_PASSWORD_IS_NULL.getCode(), BaseErrorCode.USER_PASSWORD_IS_NULL.getMessage());
        }
        SysUser sysUser = null;
        if (vo.getType() == null || vo.getType() == 1) {
            String passWd = SysUserPassWdSaltEnum.encrypt(vo.getPassWd());
            SysUser sysUserCondition = new SysUser();
            sysUserCondition.setPasswd(passWd);
            sysUserCondition.setUserAccount(vo.getUserAccount());
            List<SysUser> sysUserList = sysUserDomain.listByPara(sysUserCondition, null);
            if (CollectionUtils.isEmpty(sysUserList)) {
                throw new BaseException(SysUserErrorCode.ACCOUNT_OR_PASSWORD_ERROR.getCode(), SysUserErrorCode.ACCOUNT_OR_PASSWORD_ERROR.getMessage());
            }
            sysUser = sysUserList.get(0);
        } else if (vo.getType() == 2) {
            // 钉钉登录
            UserGetResponse userGetResponse = dingService.getUserGetResponse(vo.getUserAccount());
            if (userGetResponse == null || StringUtils.isEmpty(userGetResponse.getMobile())) {
                throw new BaseException(SysUserErrorCode.USER_IS_NOT_GROUP.getCode(), SysUserErrorCode.USER_IS_NOT_GROUP.getMessage());
            }
            // 通过手机号获取用户信息
            sysUser = sysUserDomain.getByPhone(userGetResponse.getMobile());
        }
        if (sysUser == null) {
            throw new BaseException(SysUserErrorCode.USER_IS_NOT_EXIST.getCode(), SysUserErrorCode.USER_IS_NOT_EXIST.getMessage());
        }
        LoginUserInfoResVO loginUserInfoResVO = new LoginUserInfoResVO();
        if (StringUtils.isNotEmpty(sysUser.getEmployeeCode())) {
            SysEmployee sysEmployee = sysEmployeeDomain.selectByEmployeeCode(sysUser.getEmployeeCode());
            if (null != sysEmployee) {
                loginUserInfoResVO.setEmployeeId(sysEmployee.getId());
            }
        }
        BeanUtils.copyProperties(sysUser, loginUserInfoResVO);
        loginUserInfoResVO.setUserId(sysUser.getId());
        loginUserInfoResVO.setUserCode(sysUser.getUserAccount());
        return BaseResult.buildSuccess(loginUserInfoResVO);
    }

    /**
     * 根据用户的名称获取符合条件的用户信息列表
     *
     * @param paramVO 用户名
     * @return 用户列表
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<UserInfoResVO>> qryUserList(SelectUserListReqVO paramVO) {
        // 检查参数合法性
        if (null == paramVO) {
            return BaseResult.buildError("参数不能为空");
        }
        if (StringUtils.isEmpty(paramVO.getUserName())
                && CollectionUtils.isEmpty(paramVO.getUserIdList())
                && CollectionUtils.isEmpty(paramVO.getEmployeeCodeList())) {
            return BaseResult.buildError("userName,userIdList,employeeCodeList不能全部为空");
        }
        /*
        if (!CollectionUtils.isEmpty(paramVO.getUserIdList()) && paramVO.getUserIdList().size() > Constants.BATCH_QUERY_COUNT) {
            return BaseResult.buildError("userIdList一次查询数量不能超过:" + Constants.BATCH_QUERY_COUNT);
        }
        if (!CollectionUtils.isEmpty(paramVO.getEmployeeCodeList()) && paramVO.getEmployeeCodeList().size() > Constants.BATCH_QUERY_COUNT) {
            return BaseResult.buildError("employeeCodeList一次查询数量不能超过:" + Constants.BATCH_QUERY_COUNT);
        }
        */

        // 执行查询
        SysUser sysUser = new SysUser();
        sysUser.setUserNameKey(paramVO.getUserName());
        sysUser.setEmployeeCodeList(paramVO.getEmployeeCodeList());
        sysUser.setUserIdList(paramVO.getUserIdList());
        sysUser.setIsDeleted(paramVO.getIsDeleted());
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<String, Object>();
        sortMap.put("id", "desc");
        // TODO 查询全量数据 OK
        List<SysUser> sysUserList = sysUserDomain.listByParaDefaultAll(sysUser, sortMap);
        // List<SysUser> sysUserList = sysUserDomain.listByPara(sysUser, sortMap);
        List<UserInfoResVO> resVOList = new ArrayList<>();
        sysUserList.forEach(item -> {
            UserInfoResVO userInfoResVO = new UserInfoResVO();
            userInfoResVO.setUserId(item.getId());
            userInfoResVO.setUserName(item.getUserName());
            userInfoResVO.setEmployeeCode(item.getEmployeeCode());
            //返回值增加员工账号
            userInfoResVO.setUserAccount(item.getUserAccount());
            userInfoResVO.setIsDeleted(item.getIsDeleted());
            resVOList.add(userInfoResVO);
        });
        return BaseResult.buildSuccess(resVOList);
    }

    /**
     * 查询用户详情接口
     *
     * @param paramVO 用户标识
     * @return 用户详情
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<RpcUserInfoVO> qryUserInfo(SelectUserInfoReqVO paramVO) {
        // 开关打开走缓存
        if (sysUserCacheService.isOpenQueryUserCacheSwatch()
                && StringUtils.isEmpty(paramVO.getIsDeleted())) {
            try {
                return sysUserCacheService.qryUserInfoFromCache(paramVO);
            } catch (Exception ex) {
                log.error("qryUserInfoFromCache Exception", ex);
            }
        }
        log.info(Constants.TIP_CACHE_NOT_OPEN);

        // 开关没有打开走原逻辑
        SysUser sysUser = null;
        String isDeleted = "N";
        if (!StringUtils.isEmpty(paramVO.getIsDeleted())) {
            isDeleted = paramVO.getIsDeleted();
        }

        // 用户信息
        if (!ObjectUtils.isEmpty(paramVO.getUserId())) {
            sysUser = sysUserDomain.getByIdDefaultAll(paramVO.getUserId(), isDeleted);
        } else if (!ObjectUtils.isEmpty(paramVO.getEmployeeCode())) {
            sysUser = sysUserDomain.getOneByEmployeeCodeDefaultAll(paramVO.getEmployeeCode(), isDeleted);
        } else if (!ObjectUtils.isEmpty(paramVO.getUserAccount())) {
            sysUser = sysUserDomain.getByUserAccountDefaultAll(paramVO.getUserAccount(), isDeleted);
        }
        if (ObjectUtils.isEmpty(sysUser)) {
            return BaseResult.buildError("没有查到该用户");
        }

        RpcUserInfoVO rpcUserInfoVO = new RpcUserInfoVO();
        BeanUtils.copyProperties(sysUser,rpcUserInfoVO);
        Long userId = sysUser.getId();
        log.info("UserFeignService qryUserInfo() rpcUserInfoVO.userId:{}", userId);
        rpcUserInfoVO.setUserId(userId);

        // 查询角色列表
        List<UserRoleInfoResVO> userRoleInfoResVOS = sysUserRoleDomain.selectRoleListByUserIdDefaultAll(userId, null, isDeleted);
        List<UserRoleResVO> roleList = new ArrayList<>();
        userRoleInfoResVOS.forEach(userRoleInfoResVO -> {
            UserRoleResVO userRoleResVO = new UserRoleResVO();
            BeanUtils.copyProperties(userRoleInfoResVO, userRoleResVO);
            roleList.add(userRoleResVO);
        });
        rpcUserInfoVO.setRoleList(roleList);

        // 查询用户关联的员工
        SysEmployee sysEmployee = sysUserEmployeeDomain.selectEmployeeByUserIdDefaultAll(userId, isDeleted);
        // 用户关联员工
        if (!ObjectUtils.isEmpty(sysEmployee)) {
            // 员工信息
            UserEmployeeResVO employeeInfo = new UserEmployeeResVO();
            BeanUtils.copyProperties(sysEmployee, employeeInfo);
            employeeInfo.setEmployeeId(sysEmployee.getId());
            rpcUserInfoVO.setEmployeeInfo(employeeInfo);
            if(null != rpcUserInfoVO && StringUtils.isEmpty(rpcUserInfoVO.getEmployeeCode())){
                rpcUserInfoVO.setEmployeeCode(sysEmployee.getEmployeeCode());
            }
            // 岗位列表
            List<UserPositionResVO> positionList = new ArrayList<>();
            Long employeeId = sysEmployee.getId();
            List<EmployeePositionResVO> employeePositionResVOS = sysEmployeePositionDomain.selectEmployeePositionListByEmployeeIdDefaultAll(employeeId, isDeleted);
            employeePositionResVOS.forEach(item -> {
                UserPositionResVO positionResVO = new UserPositionResVO();
                positionResVO.setPositionId(item.getEmployeePositionId());
                positionResVO.setPositionName(item.getPositionName());
                positionResVO.setIsDeletedPosition(item.getIsDeletedPosition());
                positionResVO.setIsDeletedEmployeePositionRel(item.getIsDeletedEmployeePositionRel());
                positionList.add(positionResVO);
            });
            rpcUserInfoVO.setPositionList(positionList);
            // 组织信息
            List<EmployeeOrgResVO> employeeOrgResVOS = sysEmployeeOrgDomain.selectEmployeeOrgListByEmployeeIdDefaultAll(employeeId, isDeleted);
            List<UserOrgResVO> orgList = new ArrayList<>();
            // 默认组织信息
            AtomicReference<UserOrgResVO> primaryOrg = new AtomicReference<>();
            employeeOrgResVOS.forEach(item -> {
                UserOrgResVO userOrgResVO = new UserOrgResVO();
                userOrgResVO.setOrgId(item.getEmployeeOrgId());
                userOrgResVO.setOrgName(item.getOrgName());
                userOrgResVO.setUuid(item.getUuid());
                userOrgResVO.setOrgCode(item.getOrgCode());
                userOrgResVO.setIsPrimaryOrg(item.getIsPrimaryOrg());
                userOrgResVO.setIsDeletedOrg(item.getIsDeletedOrg());
                userOrgResVO.setIsDeletedEmployeeOrgRel(item.getIsDeletedEmployeeOrgRel());
                if (YesOrNo.Y.name().equals(item.getIsPrimaryOrg())) {
                    primaryOrg.set(userOrgResVO);
                }
                orgList.add(userOrgResVO);
            });
            rpcUserInfoVO.setOrgList(orgList);
            // 当前操作组织信息
            SysCurrentOrg sysCurrentOrg = sysCurrentOrgDomain.getByUserId(userId);
            if (!ObjectUtils.isEmpty(sysCurrentOrg)) {
                String orgCode = sysCurrentOrg.getOrgCode();
                List<String> orgCodeList = orgList.stream().map(UserOrgResVO::getOrgCode).collect(Collectors.toList());
                // 1.如果用户所在组织包含当前组织编码，则设置为当前组织，否则设置默认组织
                if (orgCodeList.contains(orgCode)) {
                    rpcUserInfoVO.setCurrentOrgCode(orgCode);
                }
            }
            // 2.设置默认组织信息
            if (ObjectUtils.isEmpty(rpcUserInfoVO.getCurrentOrgCode()) && !ObjectUtils.isEmpty(primaryOrg.get())) {
                rpcUserInfoVO.setCurrentOrgCode(primaryOrg.get().getOrgCode());
            }
            // 用户组列表
            SelectGroupPageRequestVO groupParam = new SelectGroupPageRequestVO();
            groupParam.setEmployeeId(employeeId);
            List<UserGroupResVO> userGroupList=new ArrayList<>();
            rpcUserInfoVO.setUserGroupList(userGroupList);
            List<Long> groupIdList = new ArrayList<>(sysGroupDomain.getGroupIdSetByEmployeeCondition(groupParam));
            if (!CollectionUtils.isEmpty(groupIdList)) {
                List<SysGroup> sysGroupList = sysGroupDomain.getListByIds(groupIdList);
                if (!CollectionUtils.isEmpty(sysGroupList)) {
                    sysGroupList.forEach(item -> {
                        UserGroupResVO userGroup = new UserGroupResVO();
                        userGroup.setGroupId(item.getId());
                        userGroup.setGroupName(item.getGroupName());
                        userGroup.setUuid(item.getUuid());
                        userGroupList.add(userGroup);
                    });
                }
            }
        }
        return BaseResult.buildSuccess(rpcUserInfoVO);
    }

    /**
     * 查询用户标识列表查询对应的用户名映射关系
     *
     * @param vo 用户标识
     * @return 用户映射关系
     */
    @Override
    public BaseResult<Map<Long, String>> qryUserNameMap(List<Long> vo) {
        if (CollectionUtils.isEmpty(vo)) {
            return BaseResult.buildSuccess(Collections.emptyMap());
        }
        Map<Long, SysUser> longSysUserMap = sysUserDomain.qryUserMapByIdList(vo);
        Map<Long, String> collect = longSysUserMap.entrySet().stream()
                .filter(map -> StringUtils.isNotEmpty(map.getValue().getUserName()))
                .collect(Collectors.toMap(Map.Entry::getKey, v -> v.getValue().getUserName(), (v1, v2) -> v2));
        return BaseResult.buildSuccess(collect);
    }

    /**
     * 根据员工code集合查询员工code和用户id的对应关系map集合
     *
     * @param vo 用户标识
     * @return 用户映射关系
     */
    @Override
    public BaseResult<Map<String, Long>> qryUserIdMapByEmployeeCodes(List<String> vo) {
        if (CollectionUtils.isEmpty(vo)) {
            return BaseResult.buildSuccess(Collections.emptyMap());
        }
        if(vo.size() > Constants.BATCH_QUERY_COUNT){
            return BaseResult.buildError("批量查询不能超过"+Constants.BATCH_QUERY_COUNT+"条");
        }
        Map<String, SysUser> sysUserMap = sysUserDomain.qryUserMapByEmployeeCodes(vo);
        Map<String, Long> collect = sysUserMap.entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, v -> v.getValue().getId(), (v1, v2) -> v2));
        return BaseResult.buildSuccess(collect);
    }


    @Override
    public BaseResult authByUser(FeignAuthByUserReqVO authVO) {
        boolean flag = false;
        long userId = authVO.getUserId();
        long resourceId = authVO.getResourceId();
        String actionCode = authVO.getActionCode();
        String appCode = authVO.getAppCode();

        FeignSelectResourceActionListByUserReqVO vo = new FeignSelectResourceActionListByUserReqVO();
        vo.setUserId(userId);
        vo.setAppCode(appCode);

        BaseResult<Set<FeignSelectResourceActionListVO>> br = selectResourceActionListByUser(vo);
        Set<FeignSelectResourceActionListVO> resourceActionList = br.getData();
        //检查用户包含的资源权限是否包含请求中的资源动作组
        for (FeignSelectResourceActionListVO tmpVO : resourceActionList) {
            if (tmpVO.getResourceId() == resourceId && tmpVO.getActionCode().equals(actionCode)) {
                flag = true;
                break;
            }
        }

        if (flag == true) {
            return BaseResult.buildSuccess("User authorization success");
        } else {
            return BaseResult.buildError("User authorization failure");
        }
    }


    @Override
    public BaseResult<Set<FeignSelectResourceActionListVO>> selectResourceActionListByUser(FeignSelectResourceActionListByUserReqVO vo) {
        SelectRoleListByUserRequestVO roleByUserVO = new SelectRoleListByUserRequestVO();
        long userId = vo.getUserId();
        String appCode = vo.getAppCode();
        roleByUserVO.setUserId(userId);
        roleByUserVO.setAppCode(appCode);
        List<String> roleList = sysUserDomain.selectRoleListByUser(roleByUserVO);
        Set<FeignSelectResourceActionListVO> result = new HashSet<>();

        for (String roleCode : roleList) {
            SelectResourceActionListByRoleReqVO selectByRoleVO = new SelectResourceActionListByRoleReqVO();
            selectByRoleVO.setRoleCode(roleCode);
            selectByRoleVO.setAppCode(appCode);
            List<SelectResourceActionListVO> tmp_vo_list = sysRoleResourceActionDomain.selectResourceActionListByRoleReq(selectByRoleVO);
            List<FeignSelectResourceActionListVO> resourceActionList = new ArrayList<>();
            for (SelectResourceActionListVO each_vo : tmp_vo_list) {
                FeignSelectResourceActionListVO new_vo = new FeignSelectResourceActionListVO();
                BeanUtils.copyProperties(each_vo, new_vo);
                resourceActionList.add(new_vo);
            }
            for (FeignSelectResourceActionListVO raVO : resourceActionList) {
                result.add(raVO);
            }
        }
        return BaseResult.buildSuccess(result);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<RpcUserInfoVO>> qryUserInfoByUserListOrAppCode(SelectUserListInfoReqVo vo) {
        if (vo == null) {
            throw new BaseException(BaseErrorCode.ROLEID_OR_APPCODE_LIST_IS_NULL_OR_EMPTY.getCode(), BaseErrorCode.ROLEID_OR_APPCODE_LIST_IS_NULL_OR_EMPTY.getMessage());
        }
        if ((vo.getEmailList() == null || vo.getEmailList().size() == 0)
                && (vo.getMobilephoneList() == null || vo.getMobilephoneList().size() == 0)
                && (vo.getUserIdList() == null || vo.getUserIdList().size() == 0)
                && (vo.getAppCode() == null)
                && (vo.getEmployeeCodeList() == null || vo.getEmployeeCodeList().size() == 0)) {
            throw new BaseException(BaseErrorCode.ROLEID_OR_APPCODE_LIST_IS_NULL_OR_EMPTY.getCode(), BaseErrorCode.ROLEID_OR_APPCODE_LIST_IS_NULL_OR_EMPTY.getMessage());
        }
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<String, Object>();
        sortMap.put("su.id", "desc");
        List<RpcUserInfoVO> list = sysUserDomain.qryUserInfoByUserListOrAppCode(vo, sortMap);
        return BaseResult.buildSuccess(list);
    }

    private BaseResult<List<UserOrgInfoResVO>> privGetOrgsByUser(GetUserOrgsReqVO paramVo) {
        List<UserOrgInfoResDTO> userOrgInfoResDTOS = sysUserDomain.getOrgsByUser(paramVo);
        List<UserOrgInfoResVO> result = ConverterUtil.getInstance().mapAsList(userOrgInfoResDTOS, UserOrgInfoResVO.class);
        return BaseResult.buildSuccess(result);
    }

    /**
     * 根据用户查询组织列表
     *
     * @param paramVo 用户信息
     * @return
     */
    @Override
    public BaseResult<List<UserOrgInfoResVO>> getOrgsByUser(GetUserOrgsReqVO paramVo) {
        if (ObjectUtils.isEmpty(paramVo.getUserId())
                && StringUtil.isAllEmpty(paramVo.getUserName(), paramVo.getUserAccount(), paramVo.getEmployeeCode())) {
            return BaseResult.buildError(-1, "参数不合法！userId,userName,userAccount,employeeCode都为空。");
        }
        if(StringUtils.isEmpty(paramVo.getIsDeleted())){
            paramVo.setIsDeleted(YesOrNo.N.name());//为空默认赋值未删除
        }
        return privGetOrgsByUser(paramVo);
    }

    @Override
    public BaseResult<List<UserOrgInfoResVO>> getOrgsByUserDefaultAll(GetUserOrgsReqVO paramVo) {
        return privGetOrgsByUser(paramVo);
    }


    /**
     * 通过租户编码分页查询用户信息
     *
     * @param vo
     * @return
     */
    @Override
    public BaseResult selectPageByApp(SelectUserListByAppRequestVO vo) {
        if (null == vo) {
            return BaseResult.buildError(BaseErrorCode.PARAM_IS_NULL.getCode(), BaseErrorCode.PARAM_IS_NULL.getMessage());
        }
        if (null == vo.getPageIndex() || vo.getPageIndex() < 0) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_PAGE_INDEX_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_INDEX_ERROR.getMsg());
        }
        if (null == vo.getPageSize() || vo.getPageSize() <= 0) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_PAGE_SIZE_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_SIZE_ERROR.getMsg());
        }
        com.alibaba.algo.cooperation.usercomponent.vo.req.user.SelectUserListByAppRequestVO qryVO =
                new com.alibaba.algo.cooperation.usercomponent.vo.req.user.SelectUserListByAppRequestVO();
        BeanUtils.copyProperties(vo, qryVO);
        return sysUserService.selectPageByApp(qryVO);
    }

    /**
     * 通过租户编码分页查询用户信息
     *
     * @param vo
     * @return
     */
    @Override
    public BaseResult selectPageEntity(SelectUserListByAppRequestVO vo) {
        if (null == vo) {
            return BaseResult.buildError(BaseErrorCode.PARAM_IS_NULL.getCode(), BaseErrorCode.PARAM_IS_NULL.getMessage());
        }
        if (null == vo.getPageIndex() || vo.getPageIndex() < 0) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_PAGE_INDEX_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_INDEX_ERROR.getMsg());
        }
        if (null == vo.getPageSize() || vo.getPageSize() <= 0) {
            return BaseResult.buildError(GlobalResultStatus.PARAM_PAGE_SIZE_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_SIZE_ERROR.getMsg());
        }
        if (vo.getPageSize() > 50) {
            throw new BaseException(GlobalResultStatus.PARAM_PAGE_MAX_SIZE_OVERSIZE_ERROR.getCode(), GlobalResultStatus.PARAM_PAGE_MAX_SIZE_OVERSIZE_ERROR.getMsg());
        }
        SelectUserListRequestVO qryVO = new SelectUserListRequestVO();
        BeanUtils.copyProperties(vo, qryVO);
        return sysUserService.selectPageEntity(qryVO);
    }

    @Override
    public BaseResult update(UpdateUserReqVO vo) {
        // 1.校验用户信息
        sysUserDomain.checkLoginUserInfo(vo);
        // 2.更新工号
        String employeeCode = vo.getEmployeeCode();
        SysEmployee sysEmployee = sysEmployeeDomain.selectEmployeeByEmployeeCode(employeeCode);
        if (ObjectUtils.isEmpty(sysEmployee)) {
            log.error(SysEmployeeErrorCode.EMPLOYEE_CODE_IS_NOT_EXIST.getMessage());
            throw new BaseException(SysEmployeeErrorCode.EMPLOYEE_CODE_IS_NOT_EXIST.getCode(), SysEmployeeErrorCode.EMPLOYEE_CODE_IS_NOT_EXIST.getMessage());
        }
        Long employeeId = sysEmployee.getId();
        Long userId = vo.getUserId();
        sysUserEmployeeDomain.checkAndAddRelation(userId, employeeId);
        // 3.更新员工信息
        UpdateEmployeeRequestVO updateEmployeeRequestVO = new UpdateEmployeeRequestVO();
        BeanUtils.copyProperties(vo, updateEmployeeRequestVO);
        updateEmployeeRequestVO.setId(employeeId);
        return sysEmployeeService.update(updateEmployeeRequestVO);
    }

    @Override
    public BaseResult resetPassWd(ResetUserPassWordReqVO vo) {
        // 1.校验用户信息
        sysUserDomain.checkLoginUserInfo(vo);
        // 2.校验密码
        String oldPasswd;
        String passwd;
        try {
            oldPasswd = RSAUtils.decryptByPriKey(vo.getOldPasswd(), rsaPrivateKey);
            passwd = RSAUtils.decryptByPriKey(vo.getPasswd(), rsaPrivateKey);
        } catch (Exception e) {
            log.error("密码解析错误,e:{}", e);
            throw new BaseException(SysUserErrorCode.ACCOUNT_OR_PASSWORD_ERROR.getCode(), SysUserErrorCode.ACCOUNT_OR_PASSWORD_ERROR.getMessage());
        }
        sysUserDomain.checkPasswd(vo.getUserId(),oldPasswd);
        ResetUserPassWord resetUserPassWord = new ResetUserPassWord();
        BeanUtils.copyProperties(vo, resetUserPassWord);
        resetUserPassWord.setPasswd(passwd);
        return sysUserService.resetPassWd(resetUserPassWord);
    }

    @Override
    public BaseResult checkUserPermissions(CheckUserPermissionsReqVO vo) {
        // 数据检查
        if (vo == null ||
                (null == vo.getUserId() && StringUtils.isEmpty(vo.getUserAccount()) && org.apache.commons.collections4.CollectionUtils.isEmpty(vo.getRoleIdList()))
                || StringUtils.isEmpty(vo.getAppCode())
                || StringUtils.isEmpty(vo.getResourcePath())) {
            throw new BaseException(GlobalResultStatus.PARAM_ERROR.getCode(), GlobalResultStatus.PARAM_ERROR.getMsg());
        }

        // 检查租户下是否配置了该资源
        SelectAppResourceReqVO selectAppResourceReqVO = new SelectAppResourceReqVO();
        selectAppResourceReqVO.setAppCode(vo.getAppCode());
        List<String> resourcesPathList = new ArrayList<>(1);
        resourcesPathList.add(vo.getResourcePath());
        selectAppResourceReqVO.setResourcePathList(resourcesPathList);
        List<ResourceResVO> resourceResVOList = sysResourceDomain.qryResourceListByAppOrPath(selectAppResourceReqVO);
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(resourceResVOList)) {
            return BaseResult.buildSuccess("没有配置的路径，不做检查", true);
        }

        // 获取角色清单
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(vo.getRoleIdList())) {
            List<UserRoleInfoResVO> userRoleInfoResVOList = sysUserRoleDomain.selectRoleListByUserIdAndApp(vo.getUserId(), null, vo.getUserAccount(), vo.getAppCode(), null);
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(userRoleInfoResVOList)) {
                throw new BaseException(SysUserErrorCode.ACCOUNT_OR_PASSWORD_ERROR.getCode(), SysUserErrorCode.ACCOUNT_OR_PASSWORD_ERROR.getMessage());
            }
            List<Long> roleIdList = new ArrayList<>(userRoleInfoResVOList.size());
            for (UserRoleInfoResVO item : userRoleInfoResVOList) {
                roleIdList.add(item.getRoleId());
            }
            vo.setRoleIdList(roleIdList);
        }

        // 查询资源列表
        List<ResourceResVO> rtnResourceResVOList = sysRoleResourceDomain.selectResourceListByRoleAppPath(vo);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(rtnResourceResVOList)) {
            return BaseResult.buildSuccess("Check Permissions Success");
        } else {
            return BaseResult.buildError("No Permissions");
        }
    }

    @Override
    public BaseResult getUserBySessionId(CurrentUserReqVO vo) {
        if(null==vo || StringUtils.isEmpty(vo.getXxlSsoSessionid())){
            return BaseResult.buildError("参数缺失");
        }

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String pClientId=request.getHeader("clientId");
        String pClientSecret=request.getHeader("clientSecret");
        if(StringUtils.isEmpty(pClientId)||StringUtils.isEmpty(pClientSecret)){
            return BaseResult.buildError("clientId或clientSecret为空");
        }
        if(!clientId.equals(pClientId) || !clientSecret.equals(pClientSecret)){
            return BaseResult.buildError("无权访问");
        }

        XxlSsoUser xxlSsoUser = SsoTokenLoginHelper.loginCheck(vo.getXxlSsoSessionid());
        if(ObjectUtils.isEmpty(xxlSsoUser)){
            return BaseResult.buildError("用户未登录,无法获取用户信息");
        }
        SysUser sysUser=sysUserDomain.getById(Long.valueOf(xxlSsoUser.getUserid()));
        if(ObjectUtils.isEmpty(sysUser)){
            return BaseResult.buildError("该用户不存在");
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("userId",xxlSsoUser.getUserid());
        jsonObject.put("userName",xxlSsoUser.getUsername());
        jsonObject.put("userAccount",sysUser.getUserAccount());
        jsonObject.put("employeeCode", sysUser.getEmployeeCode());
        return BaseResult.buildSuccess(jsonObject);
    }

    @Override
    public BaseResult selectUserAllInfoByUserIdOrUserCode(UserAllInfoReqVO vo) {
        UserAllInfoRequestVO userAllInfoRequestVO = new UserAllInfoRequestVO();
        BeanUtils.copyProperties(vo, userAllInfoRequestVO);
        return sysUserService.selectUserAllInfoByUserIdOrUserCode(userAllInfoRequestVO);
    }

    @Override
    public BaseResult selectUserAllInfoByUserIdOrUserCode1(UserAllInfoReqVO vo) {
        return selectUserAllInfoByUserIdOrUserCode(vo);
    }

    @Override
    public BaseResult checkEmpIsNotActive(CheckEmpReqVO vo) {
        if (ObjectUtils.isEmpty(vo) || CollectionUtils.isEmpty(vo.getEcodes())) {
            return new BaseResult<>();
        }
        List result = sysUserDomain.checkEmpIsNotActive(vo.getEcodes());
        return BaseResult.buildSuccess(result);
    }

    @Override
    public BaseResult<Integer> getRegisteredUserCount(){
        Integer registeredUserCount = sysUserDomain.getRegisteredUserCount();
        return BaseResult.buildSuccess(registeredUserCount);
    }
}
